library(haven)
library(sp)
library(rgdal)
library(rgeos)
library(RColorBrewer)
library(cshapes)
library(maptools)
library(raster)
library(gtools)

murdock <- read_dta("data/ethnographic_atlas_fixed.dta")
coords <- subset(murdock, select=c(v106, v104))
murdock <- subset(murdock, select=c(v72,v33))

#coding the election and statehood variables
table(murdock$v72)
murdock$election <- 0
murdock$election[murdock$v72==6] <- 1
murdock$election[murdock$v72==7] <- 1
murdock$statehood <- as.numeric(as.character(as.factor(murdock$v33)))
murdock$numgroups <-1 
murdock <- subset(murdock, select=c(statehood, election, numgroups,v72))

murdock <- SpatialPointsDataFrame(coords, murdock, proj4string=CRS(as.character("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0")))



c <- readOGR("data/shapefiles/CShapes-2.0.shp", layer="CShapes-2.0")
cs <- subset(c, gweyear==2019)

#color 
murdock@data$col[murdock$election==1] <- "black"
murdock@data$col[murdock$election==0] <- "grey"

murdock@data$pch[murdock$election==0] <- 17
murdock@data$pch[murdock$election==1] <- 16


c2 <- gUnaryUnion(c)

#crop
extent(c2)
c2 <- crop(c2, extent(-175, 175, -55, 75))
#plot(out, col="khaki", bg="azure2")

#margins
par(oma=c(0, 0, 0, 0))
par(mar=c(0, 0, 0, 0))
par(plt=c(0, 1, 0, 1))


#plotting
tiff("output/map_2_1.tiff", width = 9, height = 5.5, units = 'in', res = 300)
par(mar = rep(0, 4))
plot(c2)
plot(murdock, col=murdock$col, add=T, pch=murdock$pch, cex=.5)
legend("bottom", legend=c("Election or consensus (informal or formal)","No election or consensus"), col=c("red", "grey"), pch=c(16,17))
dev.off()
